//
//  QBDropDownMenuTitleButton.swift
//  QBDropDownMenuDemo
//
//  Created by 乐启榜 on 16/7/25.
//  Copyright © 2016年 乐启榜. All rights reserved.
//

import UIKit
import SnapKit

class QBDropDownMenuTitleButton: UIButton {
    
    var index: NSInteger = 0
    private var mainTitle: String = ""
    
    private lazy var arrowView: UIView = {
        let arrowView = UIView()
        return arrowView
    }()
    private lazy var shareLayer: CAShapeLayer = {
        let shareLayer: CAShapeLayer = CAShapeLayer()
        let path: UIBezierPath = UIBezierPath()
        path.moveToPoint(CGPoint(x: 0, y: 0))
        path.addLineToPoint(CGPoint(x: dropDownMenuTitleButtonUIValue().ARROWVIEW_WIDTH, y: 0))
        path.addLineToPoint(CGPoint(x: dropDownMenuTitleButtonUIValue().ARROWVIEW_WIDTH * 0.5, y: dropDownMenuTitleButtonUIValue().ARROWVIEW_HEIGHT))
        path.closePath()
        shareLayer.path = path.CGPath
        shareLayer.fillColor = kDropdownMenuIndicatorColor().CGColor
        return shareLayer
    }()
    private lazy var bottomSeperator: UIView = {
        let bottomSeperator = UIView()
        bottomSeperator.backgroundColor = kDropdownMenuSeperatorColor()
        return bottomSeperator
    }()
    private lazy var bottomLineView: UIView = {
        let bottomLineView = UIView()
        bottomLineView.backgroundColor = kDropdownMenuIndicatorColor()
        return bottomLineView
    }()
    private lazy var mainTitleLabel: UILabel = {
        let mainTitleLabel = UILabel()
        mainTitleLabel.text = self.mainTitle
        mainTitleLabel.font = UIFont.systemFontOfSize(dropDownMenuTitleButtonUIValue().MAINTITLELABEL_FONT)
        mainTitleLabel.adjustsFontSizeToFitWidth = true
        mainTitleLabel.textColor = kDropdownMenuTitleColor()
        return mainTitleLabel
    }()
    private lazy var subTitleLabel: UILabel = {
        let subTitleLabel = UILabel()
        subTitleLabel.font = UIFont.systemFontOfSize(dropDownMenuTitleButtonUIValue().SUBTITLELABEL_FONT)
        subTitleLabel.textAlignment = .Center
        subTitleLabel.textColor = kDropdownMenuIndicatorColor()
        return subTitleLabel
    }()
    
    var arrowColor: UIColor? {
        didSet{
            self.shareLayer.fillColor = arrowColor?.CGColor
        }
    }
    var mainTitleColor: UIColor?{
        didSet{
            self.mainTitleLabel.textColor = mainTitleColor
        }
    }
    
    var subTitleColor: UIColor?{
        didSet{
            self.subTitleLabel.textColor = subTitleColor
        }
    }
    var subTitle: String? {
        didSet {
            self.subTitleLabel.text = subTitle
        }
    }
    
    // Init_Method
    init(maintitle: String, subtitle: String) {
        super.init(frame: CGRectZero)
        
        initWithMainTitleAndSubTitle(maintitle, subtitle: subtitle)
    }
    init(maintitle: String) {
        super.init(frame: CGRectZero)
        
        initWithMainTitleAndSubTitle(maintitle, subtitle: nil)
 
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initWithMainTitleAndSubTitle(maintitle: String?, subtitle: String?) {
        
        if let maintitle = maintitle {
            self.mainTitle = maintitle
        }
        if let subTitle = subtitle {
            self.subTitle = subTitle
        }
        self.backgroundColor = UIColor.whiteColor()
        self.adjustsImageWhenHighlighted = true
        self.viewConfig()
    }
    
    func viewConfig() {
        
        weak var weakSelf = self

        let containerView: UIView = UIView()
        containerView.userInteractionEnabled = false
        self.addSubview(containerView)
        
        containerView.addSubview(self.mainTitleLabel)
        
        let mainTitleSize: CGSize = (mainTitle.qb_stringSizeWithFont(UIFont.systemFontOfSize(dropDownMenuTitleButtonUIValue().MAINTITLELABEL_FONT)))
        let subTitleSize: CGSize = (mainTitle.qb_stringSizeWithFont(UIFont.systemFontOfSize(dropDownMenuTitleButtonUIValue().SUBTITLELABEL_FONT)))
        
        if self.subTitle != nil {
            
            containerView.addSubview(self.subTitleLabel)
            
            let containerViewHeight = mainTitleSize.height + subTitleSize.height + dropDownMenuTitleButtonUIValue().SUBTITLELABEL_TOPMARGIN
            
            containerView.snp_makeConstraints(closure: { (make) in
                make.left.right.centerY.equalTo(weakSelf!)
                make.height.equalTo(containerViewHeight)
            })
            self.mainTitleLabel.snp_makeConstraints(closure: { (make) in
                make.top.centerX.equalTo(containerView)
                make.width.equalTo(mainTitleSize.width)
                make.height.equalTo(mainTitleSize.height)
            })
            self.subTitleLabel.snp_makeConstraints(closure: { (make) in
                make.left.centerX.bottom.equalTo(containerView)
                make.height.equalTo(subTitleSize.height)
            })
        }else{
            
            containerView.snp_makeConstraints(closure: { (make) in
                make.edges.equalTo(weakSelf!)
            })
            self.mainTitleLabel.snp_makeConstraints(closure: { (make) in
                make.center.equalTo(containerView)
                make.size.equalTo(mainTitleSize)
            })
        }
        
        containerView.addSubview(self.arrowView)
        self.arrowView.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((weakSelf?.mainTitleLabel.snp_right)!).offset(dropDownMenuTitleButtonUIValue().ARROWVIEW_LEFTMARGIN)
            make.centerY.equalTo((weakSelf?.mainTitleLabel)!)
            make.width.equalTo(dropDownMenuTitleButtonUIValue().ARROWVIEW_WIDTH)
            make.height.equalTo(dropDownMenuTitleButtonUIValue().ARROWVIEW_HEIGHT)
        })

        self.arrowView.layer.addSublayer(self.shareLayer)
        
        self.addSubview(self.bottomSeperator)
        bottomSeperator.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(weakSelf!)
            make.height.equalTo(dropDownMenuTitleButtonUIValue().BOTTOMSEPERATOR_HEIGHT)
        }
        
        self.addSubview(bottomLineView)
        self.bottomLineView.snp_makeConstraints(closure: { (make) in
            make.left.right.bottom.equalTo(weakSelf!)
            make.height.equalTo(dropDownMenuTitleButtonUIValue().BOTTOMLINE_HEIGHT)
        })
        
        self.bottomLineView.hidden = true
    }
    
    override var selected: Bool{
        
        didSet{
            weak var weakSelf = self
            self.bottomLineView.hidden = !selected
            self.mainTitleLabel.textColor = selected ? kDropdownMenuIndicatorColor() : kDropdownMenuTitleColor()
            if selected {
                UIView.animateWithDuration(dropDownMenuMenuUIValue().ANIMATION_DURATION, animations: {
                    weakSelf?.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            }else{
                UIView.animateWithDuration(dropDownMenuMenuUIValue().ANIMATION_DURATION, animations: {
                    weakSelf?.arrowView.transform = CGAffineTransformIdentity
                })
            }
        }
    }
}

extension String {
    
    func qb_stringSize(font: UIFont, maxWidTh: CGFloat, maxHeight: CGFloat) -> (CGSize) {

        let attr: Dictionary<String, UIFont> = [NSFontAttributeName: font]
        
        let maxSize: CGSize = CGSize(width: maxWidTh, height: maxHeight)
        
        let options: NSStringDrawingOptions = [.TruncatesLastVisibleLine,.UsesLineFragmentOrigin,.UsesFontLeading]
        
        return self.boundingRectWithSize(maxSize, options: options, attributes: attr, context: nil).size
        
    }
    
    func qb_stringSizeWithFont(font: UIFont) -> (CGSize) {
        
        return qb_stringSize(font, maxWidTh: 0, maxHeight: 0)
        
    }
    
    func qb_stingSize(font: UIFont, maxWidth: CGFloat) -> (CGSize) {
        
        return qb_stringSize(font, maxWidTh: maxWidth, maxHeight: 0)
        
    }
}
